/*
 * Copyright (C) 2014 luke.
 * 
 * This file is part of Silvie.
 * 
 * Silvie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Silvie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Silvie.  If not, see <http://www.gnu.org/licenses/>.
 */

package silvie.gui.previewers;

import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

import silvie.gui.Preview;
import silvie.gui.SilvieGUI;

/**
 * Abstract "previewer". A previewer is an object whose {@link #doPreview()}
 * method causes the Preview to display the Silver resource.
 * 
 * @author luke
 */
public abstract class AbstractPreviewer {
	protected static String previousSavedPath = null;
	protected Preview preview;
	protected File savedFile;
	protected String filterExtension;
	protected String filterDescription;

	/**
	 * AbstractPreviewer constructor.
	 * 
	 * @param preview the Preview to display on.
	 */
	public AbstractPreviewer(Preview preview) {
		this.preview = preview;
		this.savedFile = null;
		this.filterExtension = null;
		this.filterDescription = null;
	}

	/**
	 * Updates the preview to display the Silver resource.
	 */
	public abstract void doPreview();

	/**
	 * Opens a save dialog for the Silver resource. If the user validates the
	 * dialog then {@code savedFile} is set.
	 * 
	 * @return true if the user validates the dialog, false otherwise.
	 */
	public boolean save() {
		JFileChooser chooser = new JFileChooser(previousSavedPath);
		chooser.setDialogTitle(SilvieGUI.SAVE_DIALOG_MESSAGE);
		FileNameExtensionFilter filter = new FileNameExtensionFilter(this.filterDescription, this.filterExtension);
		chooser.setFileFilter(filter);
		boolean approved = chooser.showSaveDialog(this.preview.getFrame()) == JFileChooser.APPROVE_OPTION;
		if (approved) {
			File chosenFile = chooser.getSelectedFile();
			previousSavedPath = chosenFile.getParent();
			String dotExtension = "." + this.filterExtension;
			this.savedFile = new File(chosenFile.getAbsolutePath() + (chosenFile.getName().toLowerCase().endsWith(dotExtension) ? "" : dotExtension));
		}
		return approved;
	}

	/**
	 * Saves the Silver resource to {@code savedFile}.
	 * 
	 * @return the saved file.
	 * @throws IOException if a file error occurs.
	 */
	public abstract File doSave() throws IOException;

	/**
	 * Closes any resource held by the previewer. It can be a thread, timer,
	 * Java3D universe etc.
	 */
	public abstract void close();
}
